import React, { useState, useEffect } from 'react';
import { 
  Card, 
  Button, 
  Row, 
  Col, 
  Select, 
  Space, 
  Typography, 
  Divider, 
  message, 
  Tag,
  Modal,
  List,
  Tooltip,
  Badge
} from 'antd';
import { 
  ThunderboltOutlined, 
  FireOutlined, 
  CloudOutlined, 
  BulbOutlined,
  ReloadOutlined,
  HistoryOutlined,
  DeleteOutlined,
  EyeOutlined
} from '@ant-design/icons';
import LotteryPrediction from './LotteryPrediction';

const { Title, Text } = Typography;
const { Option } = Select;

/**
 * 双色球智能选号组件
 * 提供多种选号算法和预测功能
 */
const LotteryNumberPicker = ({ historyData = [], isMobile = false }) => {
  // 状态管理
  const [selectedNumbers, setSelectedNumbers] = useState({ red: [], blue: [] });
  const [algorithm, setAlgorithm] = useState('random');
  const [loading, setLoading] = useState(false);
  const [pickedHistory, setPickedHistory] = useState([]);
  const [showHistory, setShowHistory] = useState(false);
  const [showPrediction, setShowPrediction] = useState(false);

  // 从localStorage加载选号历史
  useEffect(() => {
    const savedHistory = localStorage.getItem('lotteryPickHistory');
    if (savedHistory) {
      setPickedHistory(JSON.parse(savedHistory));
    }
    
    // 监听选号记录清空事件
    const handlePickingRecordsCleared = () => {
      console.log('收到选号记录清空事件，清空智能选号页面的本地历史记录');
      setPickedHistory([]);
      localStorage.removeItem('lotteryPickHistory');
    };
    
    window.addEventListener('pickingRecordsCleared', handlePickingRecordsCleared);
    
    // 清理事件监听器
    return () => {
      window.removeEventListener('pickingRecordsCleared', handlePickingRecordsCleared);
    };
  }, []);

  /**
   * 保存选号历史到数据库
   */
  const saveToHistory = async (numbers, algorithmUsed) => {
    try {
      // 导入数据库服务
      const { DatabaseService } = await import('./database.js');
      
      // 保存到统一的选号记录表
      await DatabaseService.addPickingRecord(
        numbers.red,
        numbers.blue,
        algorithmUsed,
        'smart_picker',
        '', // 备注为空
        false // 非预测记录
      );
      
      // 同时更新本地状态（用于界面显示）
      const newRecord = {
        id: Date.now(),
        numbers,
        algorithm: algorithmUsed,
        timestamp: new Date().toISOString(),
        predicted: false
      };
      
      const updatedHistory = [newRecord, ...pickedHistory.slice(0, 49)]; // 保留最近50条记录
      setPickedHistory(updatedHistory);
      
      console.log('选号记录已保存到数据库');
    } catch (error) {
      console.error('保存选号记录失败:', error);
      // 如果数据库保存失败，回退到localStorage
      const newRecord = {
        id: Date.now(),
        numbers,
        algorithm: algorithmUsed,
        timestamp: new Date().toISOString(),
        predicted: false
      };
      
      const updatedHistory = [newRecord, ...pickedHistory.slice(0, 49)];
      setPickedHistory(updatedHistory);
      localStorage.setItem('lotteryPickHistory', JSON.stringify(updatedHistory));
    }
  };

  /**
   * 随机选号算法
   */
  const randomPick = () => {
    const redNumbers = [];
    const blueNumbers = [];
    
    // 选择6个红球（1-33）
    while (redNumbers.length < 6) {
      const num = Math.floor(Math.random() * 33) + 1;
      if (!redNumbers.includes(num)) {
        redNumbers.push(num);
      }
    }
    
    // 选择1个蓝球（1-16）
    blueNumbers.push(Math.floor(Math.random() * 16) + 1);
    
    return {
      red: redNumbers.sort((a, b) => a - b),
      blue: blueNumbers
    };
  };

  /**
   * 热号选择算法 - 基于历史数据选择出现频率高的号码
   */
  const hotNumberPick = () => {
    if (!historyData || historyData.length === 0) {
      message.warning('暂无历史数据，使用随机选号');
      return randomPick();
    }

    // 统计红球和蓝球的出现频率
    const redFreq = {};
    const blueFreq = {};
    
    historyData.forEach(record => {
      if (record.red && record.blue) {
        record.red.forEach(num => {
          redFreq[num] = (redFreq[num] || 0) + 1;
        });
        record.blue.forEach(num => {
          blueFreq[num] = (blueFreq[num] || 0) + 1;
        });
      }
    });

    // 按频率排序并选择热号
    const hotReds = Object.entries(redFreq)
      .sort(([,a], [,b]) => b - a)
      .slice(0, 12)
      .map(([num]) => parseInt(num));
    
    const hotBlues = Object.entries(blueFreq)
      .sort(([,a], [,b]) => b - a)
      .slice(0, 6)
      .map(([num]) => parseInt(num));

    // 从热号中随机选择
    const selectedReds = [];
    while (selectedReds.length < 6 && hotReds.length > 0) {
      const randomIndex = Math.floor(Math.random() * hotReds.length);
      selectedReds.push(hotReds.splice(randomIndex, 1)[0]);
    }
    
    // 如果热号不够，补充随机号码
    while (selectedReds.length < 6) {
      const num = Math.floor(Math.random() * 33) + 1;
      if (!selectedReds.includes(num)) {
        selectedReds.push(num);
      }
    }

    const selectedBlue = hotBlues.length > 0 ? 
      hotBlues[Math.floor(Math.random() * hotBlues.length)] : 
      Math.floor(Math.random() * 16) + 1;

    return {
      red: selectedReds.sort((a, b) => a - b),
      blue: [selectedBlue]
    };
  };

  /**
   * 冷号选择算法 - 基于历史数据选择出现频率低的号码
   */
  const coldNumberPick = () => {
    if (!historyData || historyData.length === 0) {
      message.warning('暂无历史数据，使用随机选号');
      return randomPick();
    }

    // 统计所有号码的出现频率
    const redFreq = {};
    const blueFreq = {};
    
    // 初始化所有号码频率为0
    for (let i = 1; i <= 33; i++) {
      redFreq[i] = 0;
    }
    for (let i = 1; i <= 16; i++) {
      blueFreq[i] = 0;
    }
    
    historyData.forEach(record => {
      if (record.red && record.blue) {
        record.red.forEach(num => {
          redFreq[num]++;
        });
        record.blue.forEach(num => {
          blueFreq[num]++;
        });
      }
    });

    // 按频率排序并选择冷号
    const coldReds = Object.entries(redFreq)
      .sort(([,a], [,b]) => a - b)
      .slice(0, 12)
      .map(([num]) => parseInt(num));
    
    const coldBlues = Object.entries(blueFreq)
      .sort(([,a], [,b]) => a - b)
      .slice(0, 6)
      .map(([num]) => parseInt(num));

    // 从冷号中随机选择
    const selectedReds = [];
    while (selectedReds.length < 6) {
      const randomIndex = Math.floor(Math.random() * coldReds.length);
      const num = coldReds[randomIndex];
      if (!selectedReds.includes(num)) {
        selectedReds.push(num);
      }
    }

    const selectedBlue = coldBlues[Math.floor(Math.random() * coldBlues.length)];

    return {
      red: selectedReds.sort((a, b) => a - b),
      blue: [selectedBlue]
    };
  };

  /**
   * 智能推荐算法 - 综合多种因素的选号策略
   */
  const smartRecommend = () => {
    if (!historyData || historyData.length === 0) {
      message.warning('暂无历史数据，使用随机选号');
      return randomPick();
    }

    // 综合热号、冷号和随机的策略
    const hotNumbers = hotNumberPick();
    const coldNumbers = coldNumberPick();
    const randomNumbers = randomPick();

    // 混合选择：2个热号 + 2个冷号 + 2个随机号
    const selectedReds = [
      ...hotNumbers.red.slice(0, 2),
      ...coldNumbers.red.slice(0, 2),
      ...randomNumbers.red.slice(0, 2)
    ].sort((a, b) => a - b);

    // 蓝球随机选择热号或冷号
    const selectedBlue = Math.random() > 0.5 ? hotNumbers.blue[0] : coldNumbers.blue[0];

    return {
      red: selectedReds,
      blue: [selectedBlue]
    };
  };

  /**
   * 执行选号
   */
  const handlePick = async () => {
    setLoading(true);
    
    try {
      let result;
      
      switch (algorithm) {
        case 'hot':
          result = hotNumberPick();
          break;
        case 'cold':
          result = coldNumberPick();
          break;
        case 'smart':
          result = smartRecommend();
          break;
        default:
          result = randomPick();
      }
      
      setSelectedNumbers(result);
      await saveToHistory(result, algorithm);
      message.success('选号完成！');
      
    } catch (error) {
      message.error('选号失败，请重试');
      console.error('选号错误:', error);
    } finally {
      setLoading(false);
    }
  };

  /**
   * 渲染号码球
   */
  const renderNumberBalls = (numbers, type) => {
    const ballStyle = {
      display: 'inline-block',
      width: '32px',
      height: '32px',
      borderRadius: '50%',
      textAlign: 'center',
      lineHeight: '32px',
      margin: '2px',
      fontWeight: 'bold',
      color: 'white',
      fontSize: '14px'
    };

    const redStyle = { ...ballStyle, backgroundColor: '#ff4d4f' };
    const blueStyle = { ...ballStyle, backgroundColor: '#1890ff' };

    return numbers.map((num, index) => (
      <span 
        key={index} 
        style={type === 'red' ? redStyle : blueStyle}
      >
        {String(num).padStart(2, '0')}
      </span>
    ));
  };

  /**
   * 清除选号历史
   */
  const clearHistory = () => {
    Modal.confirm({
      title: '确认清除',
      content: '确定要清除所有选号历史吗？',
      onOk: () => {
        setPickedHistory([]);
        localStorage.removeItem('lotteryPickHistory');
        message.success('历史记录已清除');
      }
    });
  };

  /**
   * 删除单条历史记录
   */
  const deleteHistoryItem = (id) => {
    const updatedHistory = pickedHistory.filter(item => item.id !== id);
    setPickedHistory(updatedHistory);
    localStorage.setItem('lotteryPickHistory', JSON.stringify(updatedHistory));
    message.success('记录已删除');
  };

  /**
   * 预测选中的号码
   */
  const predictNumbers = (numbers) => {
    setSelectedNumbers(numbers);
    setShowPrediction(true);
  };

  const algorithmOptions = [
    { value: 'random', label: '随机选号', icon: <ThunderboltOutlined /> },
    { value: 'hot', label: '热号选择', icon: <FireOutlined /> },
    { value: 'cold', label: '冷号选择', icon: <CloudOutlined /> },
    { value: 'smart', label: '智能推荐', icon: <BulbOutlined /> }
  ];

  return (
    <div style={{ padding: isMobile ? '8px' : '16px' }}>
      <Card>
        <Title level={3} style={{ textAlign: 'center', marginBottom: '24px' }}>
          🎯 双色球智能选号系统
        </Title>

        {/* 算法选择 */}
        <Row gutter={[16, 16]} style={{ marginBottom: '24px' }}>
          <Col xs={24} sm={12}>
            <Text strong>选号算法：</Text>
            <Select
              value={algorithm}
              onChange={setAlgorithm}
              style={{ width: '100%', marginTop: '8px' }}
              size="large"
            >
              {algorithmOptions.map(option => (
                <Option key={option.value} value={option.value}>
                  {option.icon} {option.label}
                </Option>
              ))}
            </Select>
          </Col>
          <Col xs={24} sm={12}>
            <div style={{ marginTop: isMobile ? '0' : '28px' }}>
              <Space wrap>
                <Button 
                  type="primary" 
                  size="large"
                  loading={loading}
                  onClick={handlePick}
                  icon={<ThunderboltOutlined />}
                >
                  开始选号
                </Button>
                <Button 
                  size="large"
                  onClick={() => setShowHistory(true)}
                  icon={<HistoryOutlined />}
                >
                  历史记录
                  <Badge count={pickedHistory.length} showZero />
                </Button>
              </Space>
            </div>
          </Col>
        </Row>

        {/* 选号结果 */}
        {selectedNumbers.red.length > 0 && (
          <Card 
            style={{ 
              marginBottom: '24px', 
              background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)',
              border: 'none'
            }}
          >
            <div style={{ textAlign: 'center' }}>
              <Title level={4} style={{ color: 'white', marginBottom: '16px' }}>
                🎊 本期推荐号码
              </Title>
              <div style={{ marginBottom: '16px' }}>
                <Text style={{ color: 'white', marginRight: '8px' }}>红球：</Text>
                {renderNumberBalls(selectedNumbers.red, 'red')}
                <Divider type="vertical" style={{ borderColor: 'white', margin: '0 16px' }} />
                <Text style={{ color: 'white', marginRight: '8px' }}>蓝球：</Text>
                {renderNumberBalls(selectedNumbers.blue, 'blue')}
              </div>
              <Space>
                <Button 
                  type="default" 
                  ghost
                  onClick={() => predictNumbers(selectedNumbers)}
                  icon={<EyeOutlined />}
                >
                  预测分析
                </Button>
                <Button 
                  type="default" 
                  ghost
                  onClick={handlePick}
                  icon={<ReloadOutlined />}
                >
                  重新选号
                </Button>
              </Space>
            </div>
          </Card>
        )}

        {/* 算法说明 */}
        <Card title="算法说明" size="small" style={{ marginTop: '16px' }}>
          <Row gutter={[16, 8]}>
            <Col xs={24} sm={12}>
              <Tag color="blue" icon={<ThunderboltOutlined />}>随机选号</Tag>
              <Text type="secondary">完全随机生成号码</Text>
            </Col>
            <Col xs={24} sm={12}>
              <Tag color="red" icon={<FireOutlined />}>热号选择</Tag>
              <Text type="secondary">基于历史高频号码</Text>
            </Col>
            <Col xs={24} sm={12}>
              <Tag color="cyan" icon={<CloudOutlined />}>冷号选择</Tag>
              <Text type="secondary">基于历史低频号码</Text>
            </Col>
            <Col xs={24} sm={12}>
              <Tag color="purple" icon={<BulbOutlined />}>智能推荐</Tag>
              <Text type="secondary">综合多种策略分析</Text>
            </Col>
          </Row>
        </Card>
      </Card>

      {/* 选号历史弹窗 */}
      <Modal
        title={
          <Space>
            <HistoryOutlined />
            选号历史记录
            <Badge count={pickedHistory.length} showZero />
          </Space>
        }
        open={showHistory}
        onCancel={() => setShowHistory(false)}
        width={isMobile ? '95%' : 800}
        footer={[
          <Button key="clear" danger onClick={clearHistory}>
            <DeleteOutlined /> 清除全部
          </Button>,
          <Button key="close" onClick={() => setShowHistory(false)}>
            关闭
          </Button>
        ]}
      >
        <List
          dataSource={pickedHistory}
          renderItem={(item) => (
            <List.Item
              actions={[
                <Tooltip title="预测分析">
                  <Button 
                    type="link" 
                    size="small"
                    onClick={() => {
                      predictNumbers(item.numbers);
                      setShowHistory(false);
                    }}
                    icon={<EyeOutlined />}
                  />
                </Tooltip>,
                <Tooltip title="删除记录">
                  <Button 
                    type="link" 
                    size="small" 
                    danger
                    onClick={() => deleteHistoryItem(item.id)}
                    icon={<DeleteOutlined />}
                  />
                </Tooltip>
              ]}
            >
              <List.Item.Meta
                title={
                  <Space>
                    <Tag color="blue">
                      {algorithmOptions.find(opt => opt.value === item.algorithm)?.label}
                    </Tag>
                    <Text type="secondary">{item.timestamp}</Text>
                  </Space>
                }
                description={
                  <div>
                    <Text>红球：</Text>
                    {renderNumberBalls(item.numbers.red, 'red')}
                    <Divider type="vertical" />
                    <Text>蓝球：</Text>
                    {renderNumberBalls(item.numbers.blue, 'blue')}
                  </div>
                }
              />
            </List.Item>
          )}
          locale={{ emptyText: '暂无选号记录' }}
        />
      </Modal>

      {/* 预测分析弹窗 */}
      <Modal
        title="🔮 号码预测分析"
        open={showPrediction}
        onCancel={() => setShowPrediction(false)}
        width={isMobile ? '95%' : 1000}
        footer={[
          <Button key="close" onClick={() => setShowPrediction(false)}>
            关闭
          </Button>
        ]}
      >
        {showPrediction && (
          <LotteryPrediction 
            historyData={historyData} 
            isMobile={isMobile}
            selectedNumbers={selectedNumbers}
          />
        )}
      </Modal>
    </div>
  );
};

export default LotteryNumberPicker;